import 'package:cached_network_image/cached_network_image.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/badge_icon.dart';
import 'package:casdon/modules/recipe/application/notification/course_list_notifier.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_put_brower_notifier.dart';
import 'package:casdon/modules/recipe/data/model/cook_module_content_model.dart';
import 'package:casdon/modules/recipe/data/model/recipe_placeholder_data.dart';
import 'package:casdon/modules/recipe/ui/widgets/play_orverlay_button.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 每个 tag 对应的列表视图（可刷新、可分页）
class CourseListScreen extends ConsumerStatefulWidget {
  final String? tagId;
  final String? moduleId;

  const CourseListScreen({
    super.key,
    required this.tagId,
    required this.moduleId,
  });

  @override
  ConsumerState<CourseListScreen> createState() => _CourseListState();
}

class _CourseListState extends ConsumerState<CourseListScreen> {
  final _controller = ScrollController();

  @override
  void initState() {
    super.initState();
    Future.microtask(
      () => ref
          .read(
            courseListAsyncProvider((widget.moduleId!, widget.tagId)).notifier,
          )
          .refresh(),
    );
    _controller.addListener(_onScroll);
  }

  void _onScroll() {
    if (_controller.position.pixels >=
        _controller.position.maxScrollExtent - 100) {
      ref
          .read(
            courseListAsyncProvider((widget.moduleId!, widget.tagId)).notifier,
          )
          .loadMore();
    }
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(
      courseListAsyncProvider((widget.moduleId!, widget.tagId)),
    );

    return RefreshIndicator(
      onRefresh: () => ref
          .read(
            courseListAsyncProvider((widget.moduleId!, widget.tagId)).notifier,
          )
          .refresh(),
      child: ListView.builder(
        controller: _controller,
        padding: EdgeInsets.symmetric(vertical: 8.h),
        itemCount: state.value?.data.length ?? 0,
        itemBuilder: (_, i) {
          final item = state.value!.data[i];
          return Padding(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8.r),
              child: Container(
                color: Colors.white,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 封面 + 播放按钮
                    Stack(
                      alignment: Alignment.center,
                      children: [
                        CachedNetworkImage(
                          imageUrl: item.imgUrl,
                          height: 203.h,
                          width: double.infinity,
                          fit: BoxFit.cover,
                          fadeInDuration: Duration.zero,
                          placeholder: (_, __) => const SizedBox(),
                          errorWidget: (_, __, ___) {
                            return Image.network(
                              recipePlaceHolderImgUrl,
                              fit: BoxFit.cover,
                              height: 203.h,
                              width: double.infinity,
                              errorBuilder: (context, error, stackTrace) {
                                return Container(
                                  color: Colors.grey[200],
                                  child: const Icon(
                                    Icons.image_outlined,
                                    color: Colors.grey,
                                  ),
                                );
                              },
                            );
                          },
                        ),
                        // 半透明遮罩层
                        if (item.url != null && item.url!.isNotEmpty)
                          PlayOverlayButton(
                            onTap: () {
                              _handlePlayClick(ref, context, item);
                            },
                          ),
                      ],
                    ),

                    // 标题 + 浏览数
                    Padding(
                      padding: EdgeInsets.all(12.w),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: Text(
                              item.title,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: context.textTheme.bodyLarge!.copyWith(
                                color:
                                    context.customColorThemeNonNull.textColor1,
                              ),
                            ),
                          ),
                          Row(
                            children: [
                              BadgeIcon(
                                imagePath: Assets.images.icView.path,
                                size: 18.r,
                              ),
                              SizedBox(width: 4.w),
                              Text(
                                item.view,
                                style: context.textTheme.bodySmall!.copyWith(
                                  color: context
                                      .customColorThemeNonNull
                                      .textColor2,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _handlePlayClick(
    WidgetRef ref,
    BuildContext context,
    CookModuleContentModel model,
  ) {
    VideoPlayerRoute(title: model.title, url: model.url!).push(context);
    final _ = ref.read(recipePutBrowerAsyProvier(model.id));
  }
}
